package com.panopset.sf;

import java.math.BigDecimal;

import org.apache.log4j.Logger;

import com.panopset.Strings;
import com.panopset.rdb.DataProps;
import com.panopset.rdb.Store;

/**
 *
 * @author Karl Dinwiddie
 *
 */
public final class AppProps {

    /**
     * @param appSchema
     *            Application name is used for the panopset H2 relational
     *            database store.
     */
    public AppProps(final String appSchema) {
        if (Strings.isPopulated(appSchema)) {
            schema = appSchema;
        } else {
            schema = "dft";
        }
    }

    /**
     *
     * @param appSchema
     *            Application name is used for the panopset H2 relational
     *            database store.
     * @param baseDir
     *            Base directory to store h2 files within user home directory.
     */
    public AppProps(final String appSchema, final String baseDir) {
        this(appSchema);
        base = baseDir;
    }

    /**
     * @param key
     *            Key.
     * @param value
     *            Value.
     */
    public void put(final String key, final String value) {
        getDataProps().put(key, value);
    }

    /**
     * @param key
     *            Key.
     * @return value.
     */
    public String get(final String key) {
        return getDataProps().get(key);
    }

    /**
     * H2 base directory.
     */
    private String base;

    /**
     * @return H2 base directory.
     */
    private String getBase() {
        if (base == null) {
            base = Store.DFT_BASE;
        }
        return base;
    }

    /**
     * H2 schema.
     */
    private final String schema;

    /**
     * Database backed properties.
     */
    private DataProps dataProps;

    /**
     * @return Database backed properties.
     */
    public DataProps getDataProps() {
        if (dataProps == null) {
            dataProps = new DataProps(
                    new Store(Store.DEFAULT_STORE, getBase()), schema, "props");
        }
        return dataProps;
    }

    /**
     * Get integer value from props.
     *
     * @param key
     *            Key.
     * @return -1 if no value found.
     */
    public int getIntValue(final String key) {
        String s = get(key);
        if (Strings.isPopulated(s)) {
            try {
                return new BigDecimal(s).intValue();
            } catch (NumberFormatException ex) {
                Logger.getLogger(this.getClass()).warn(
                        "Return -1, can't parse " + s + " from " + key, ex);
            }
        }
        return -1;
    }

}
